package com.example.app.config;

import cn.hutool.extra.spring.SpringUtil;
import com.example.app.common.constant.Constants;
import com.example.app.entity.User;
import com.example.app.service.UserService;
import com.example.app.util.JwtUtil;
import jakarta.annotation.Resource;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.security.core.token.TokenService;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;

@Component
public class BootWebSocketInterceptor extends HttpSessionHandshakeInterceptor {
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private UserService userService;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) throws Exception {
        // 接受前端传来的参数
        String token = ((ServletServerHttpRequest) request).getServletRequest().getParameter(Constants.TOKEN_HEADER_ADMIN);
        if (StringUtils.isEmpty(token)) {
            return false;
        }
        String username = jwtUtil.extractUsername(token);
        TokenService tokenService = SpringUtil.getBean("tokenService");
        tokenService.verifyToken(token);
        User user = userService.findByUsername(username);
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getId());
        loginUser.setUser(user);
        //将参数放到attributes
        attributes.put(Constants.USER_ID, loginUser.getUserId());
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

}
